package com.amoyt.project.service.admin.impl;

import com.amoyt.project.domain.bo.LoginUser;
import com.amoyt.project.domain.dto.query.FeedbackPageQuery;
import com.amoyt.project.domain.dto.update.HandleFeedBackUpdateDto;
import com.amoyt.project.domain.pojo.Feedback;
import com.amoyt.project.domain.res.PageResult;
import com.amoyt.project.domain.res.Result;
import com.amoyt.project.mapper.FeedbackMapper;
import com.amoyt.project.service.admin.FeedBackHandleService;
import com.amoyt.project.utils.ConvertBeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @Date: 2025/8/28
 * @Time: 15:38
 * @Author: TQ_QT
 * @Description:
 */
@Service
@Slf4j
public class FeedBackHandleServiceImpl implements FeedBackHandleService {

    @Autowired
    private FeedbackMapper feedbackMapper;
    @Override
    public Result list(FeedbackPageQuery query) {
        //分页
        IPage<Feedback> page = new Page<>(query.getPage(), query.getPageSize());

        QueryWrapper<Feedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!StringUtils.isBlank(query.getFeedbackPurpose()),"feedback_purpose",query.getFeedbackPurpose());
        queryWrapper.eq(!StringUtils.isBlank(query.getIsAnonymous()),"is_anonymous",query.getIsAnonymous());
        queryWrapper.eq(!StringUtils.isBlank(query.getIsHandle()),"is_handle",query.getIsHandle());
        queryWrapper.between(query.getStartTime() != null && query.getEndTime() != null, "create_time", query.getStartTime(), query.getEndTime());
        IPage<Feedback> feedbackIPage = feedbackMapper.selectPage(page, queryWrapper);

        PageResult pageResult = PageResult.builder()
                .total(feedbackIPage.getTotal())
                .records(feedbackIPage.getRecords())
                .build();

        return Result.success(pageResult);
    }

    @Override
    public Result handleFeedBack(HandleFeedBackUpdateDto handleFeedBackDto) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //更新即可
        Feedback feedback = ConvertBeanUtils.convert(handleFeedBackDto, Feedback.class);
        feedback.setUpdateBy(loginUser.getUser().getUserId());
        feedback.setUpdateTime(LocalDateTime.now());
        feedback.setIsHandle(1);

        feedbackMapper.updateById(feedback);
        return Result.success();
    }
}
